//
//  LDUserInfoNet.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/4/23.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import SVProgressHUD
import Alamofire

class LDUserInfoNet: NSObject {
    
    //入口
    class var sharedInstance:LDUserInfoNet {
        struct Staics {
            static let instance = LDUserInfoNet()
        }
        return Staics.instance
    }
    //初始化是更新固定参数
    
    //查询 语音微简历 返回 字典
    
    
    
    //牛人端逛一逛接口
    func jobfinderSeeALittleJob(page:Int,succ:((dictArr:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.seeJobs + "\(page)"
        
        LDNetWorkManager.sharedInstance.GET(api, header: nil, success: { (value) in
            
            let data = value as? [String:AnyObject] ?? [String:AnyObject] ()
            succ(dictArr: data)
            
        }) { (data, error) in
            
            fail(err: data)
        }
        
    }
    
    //查询融云token
    func queryToken(success:((data:String)->()),failure:((data:String)->())?){
        
        
        
        let api = DDClientInfoManager.clientType() == DDClientType.Cattle ? LDJobfinderAPI.query.rongyunToken:LDEmploryAPI.query.rongyunToken
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: nil, success: { (value) in
            
            let token = value["token"] as? String ?? LDNull
            success(data: token)
            
            // 获取token的接口缓存用户姓名
            DDLoginUserManager.setAccountNamefirst(value["name"] as? String ?? "")
            // 获取token的接口缓存用户头像
            DDLoginUserManager.setDdportrait(value["logo"] as? String ?? "")
            
        }) { (data, error) in
            
            if failure != nil {
                
               failure!(data: data as? String ?? "")
            }
            
        }
        
    }
    
    //修改密码
    func changeJobfinderPassWord(dictInfo:NSDictionary,success:((data:String)->())?,failure:((data:String)->())?) {
        
        LDNetWorkManager.sharedInstance.LoginPOST(LDJobfinderAPI.set.changePassword, parameters: dictInfo as? Dictionary<String, AnyObject>, success: { (value) in
            NSOperationQueue.mainQueue().addOperationWithBlock({
                
                guard success == nil else {
                    let str = value as? String ?? String()
                    
                    guard str.characters.count > 0 else {
                        failure!(data: value as! String)
                        return
                    }
                    success!(data: value as? String ?? "成功" )
                    return
                }
                
            })
        }) { (data, error) in
            
            NSOperationQueue.mainQueue().addOperationWithBlock({
                guard failure == nil else {
                    failure!(data: data as? String ?? "失败")
                    return
                }
                
            })
            
        }
    }
    
    
    //更新状态信息
    func updateJobStatus(status_id:String,success:(()->Void)?,failure:(()->Void)?) {
        LDNetWorkManager.sharedInstance.LoginPOST(LDJobfinderAPI.set.status, parameters: ["status":status_id], success: { (value) in
            
            if success != nil {
                success!()
            }
        }) { (data, error) in
            if failure != nil {
                failure!()
            }
        }
    }
    
    //删除期望工作
    func deleteExpectJob(expectjob_id expectjob_id:String,success:(() ->())?,failure:((error:AnyObject?)->Void)?) {
        debugPrint(expectjob_id,"expectjob_id")
        LDNetWorkManager.sharedInstance.LoginPOST(LDJobfinderAPI.delete.expectedjob, parameters: ["expectjob_id":expectjob_id], success: { (value) in
            
            LDUserInfo.sharedInstance.updateUserInfo({ (dict) in
                
                if success != nil {
                    success!()
                }
                
                }, failure: { (error) in
                    if failure != nil {
                        failure!(error: nil)
                    }
            })
            
        }) { (data, error) in
            
            if failure != nil {
                failure!(error: data)
            }
        }
    }
    
    
    //切换为语音简历或文字简历
    func changeMyResumeVoiceORText(type:MyResumeType,success:((status:String)->Void)?,failure:((error:String)->Void)?) {
        
        let params = ["is_audio":type.rawValue]
        LDNetWorkManager.sharedInstance.LoginPOST(LDJobfinderAPI.set.changeVocieResume, parameters: params, success: { (value) in
            
            let data = value as? Int ?? 0
            let str = "\(data)"
            
            if success != nil {
                
                success!(status: str)
            }
            
        }) { (data, error) in
            
            if failure != nil {
                
                failure!(error: data as! String)
            }
            
        }
    }
    
    //更新语音微简历
    
    
    //上传我的优势文本
    func setMyHeightLightText(str:String?,success:((data:String?)->Void)?,failure:((error:AnyObject?)->Void)?) {
        var dict = [String:String]()
        if str == nil {
            failure!(error: "文本未编辑")
            return
        }
        dict = ["mystrengths_text":str!]
        
        LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.set.setMyStrengths, parameters: dict, success: { (value) in
            if success != nil {
                success!(data: value as? String)
            }
        }) { (data, error) in
            failure!(error: data)
        }
    }
    //牛人编辑工作经历
    //    func addJobExperience
    //牛人删除工作经历
    func deleteJobExperience(workexpid:String?,success:((value:AnyObject)->Void)?,fail:((data:AnyObject)->())?) {
        if workexpid == nil && fail != nil {
            fail!(data: "工作经历不能为空")
        } else {
            LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.delete.workexperience, parameters: ["workexperience_id":workexpid!], success: { (value) in
                success!(value: value)
            }) { (data, error) in
                fail!(data: data)
            }
        }
        
    }
    
    //牛人删除教育
    func deleteEduExp(eduexpid:String?,success:((value:AnyObject)->Void)?,fail:((data:AnyObject)->())?) {
        if eduexpid == nil && fail != nil {
            fail!(data: "工作经历不能为空")
        } else {
            LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.delete.eduexperience, parameters: ["eduexperience_id":eduexpid!], success: { (value) in
                success!(value: value)
            }) { (data, error) in
                fail!(data: data)
            }
        }
        
    }
    //增加工作经历
    
    //更新语音微简历
    func updateExpectJobVoice(api:String,success:((fileData:NSData?)->Void)?,failure:((error:NSError?)->Void)?) {
        
        let voiceBaseKey = api.componentsSeparatedByString("_").last ?? LDNull
        let fileName = voiceBaseKey.componentsSeparatedByString(".").first ?? ""
        let userID = DDLoginUserManager.userID()
        let voiceKey = String(format: "%@_%@_voice",fileName,userID)
        
        LDUserInfo.sharedInstance.userCacheManger?.removeObjectForKey(voiceKey)
        
        LDNetWorkManager.sharedInstance.LoginDOWN(api, parameters: nil, success: { (fileUrl) in
            
            let data = NSData.init(contentsOfURL: fileUrl!)
            
            dispatch_async(dispatch_get_main_queue(), {
                
//               LDUserInfo.sharedInstance.saveToCache(voiceKey, value: data! as NSData, success: nil)
                
                
                guard success == nil else {
                    success!(fileData: data)
                    return
                }
                
            })
            
            
            
            }, failure: { (error) in
                
                guard failure == nil else {
                    failure!(error: error)
                    return
                }
                
            }, progress: nil)
    }
    
    
    //查询语音微简历
    func queryExpectJobVoice(api:String,success:((fileData:NSData?)->Void)?,failure:((error:NSError?)->Void)?) {
        
        let voiceBaseKey = api.componentsSeparatedByString("_").last ?? LDNull
        let fileName = voiceBaseKey.componentsSeparatedByString(".").first ?? ""
        let userID = DDLoginUserManager.userID() ?? ""
        let voiceKey = String(format: "%@_%@_voice",fileName,userID)
        
//        LDUserInfo.sharedInstance.userCacheManger?.removeObjectForKey(voiceKey)
        LDUserInfo.sharedInstance.readFromCache(voiceKey, success: { (key, value) in
            
            
            let data = value as! NSData
            guard success == nil else {
                success!(fileData: data)
                return
            }
            
            }, failure: {
                
                LDNetWorkManager.sharedInstance.LoginDOWN(api, parameters: nil, success: { (fileUrl) in
                    
                    let data = NSData.init(contentsOfURL: fileUrl!)
                    
                    LDUserInfo.sharedInstance.saveToCache(voiceKey, value: data! as NSData, success: {
//                        _ = try? NSFileManager.defaultManager().removeItemAtPath(LDCache.JobFinderInfoVoiceResume)
                    })
                    
                    
                    guard success == nil else {
                        success!(fileData: data)
                        return
                    }
                    
                    }, failure: { (error) in
                        
                        guard failure == nil else {
                            failure!(error: error)
                            return
                        }
                        
                    }, progress: nil)
        })
    }
    
    //下载语音微简历
    func downloadMyResumeVocie(api:String,success:((fileData:NSData?)->Void)?,failure:((error:NSError?)->Void)?) {
        
//        let voiceBaseKey = api.componentsSeparatedByString("_").last ?? LDNull
//        let fileName = voiceBaseKey.componentsSeparatedByString(".").first ?? ""
//        let userID = DDLoginUserManager.userID()
//        let voiceKey = String(format: "%@_%@_voice",fileName,userID)
        
//        LDUserInfo.sharedInstance.readFromCache(voiceKey, success: { (key, value) in
//            
//            
//            let data = value as! NSData
//            guard success == nil else {
//                success!(fileData: data)
//                return
//            }
//            
//            }, failure: {
        
                LDNetWorkManager.sharedInstance.LoginDOWN(api, parameters: nil, success: { (fileUrl) in
                    
                    let data = NSData.init(contentsOfURL: fileUrl!)
                    
//                    LDUserInfo.sharedInstance.saveToCache(voiceKey, value: data! as NSData, success: {
//                        //                        _ = try? NSFileManager.defaultManager().removeItemAtPath(LDCache.JobFinderInfoVoiceResume)
//                    })
                    
                    guard success == nil else {
                        success!(fileData: data)
                        return
                    }
                    
                    }, failure: { (error) in
                        
                        guard failure == nil else {
                            failure!(error: error)
                            return
                        }
                        
                    }, progress: nil)
//        })
    }
    //删除语音微简历
    func deleteMyResumeVocie(params:[String:AnyObject],success:((fileData:AnyObject?)->Void)?,failure:((error:NSError?)->Void)?) {
        let api = LDJobfinderAPI.delete.myresumevocie
        
        LDNetWorkManager.sharedInstance.LoginPOSTSET(api, parameters: params, success: { (value) in
            
            if success != nil {
                
                NSOperationQueue.mainQueue().addOperationWithBlock({ 
                  success!(fileData: value)
                })
                
            }
        }) { (data, error) in
            if failure != nil {
                success!(fileData: data)
            }
        }
        
    }
    //设置当前的期望工作
    func setMyResumeExpCurrentJob(expectjob_id:String,success:((value:AnyObject)->Void)?,failure:((data:AnyObject)->())?) {
        
        let api = LDJobfinderAPI.set.setCurrentExpJob
        let dict = ["expectjob_id":expectjob_id]
        
//        NSOperationQueue.mainQueue().addOperationWithBlock {
        
            LDNetWorkManager.sharedInstance.LoginPOSTSET(api, parameters: dict, success: { (value) in
                
                if success != nil {
                    success!(value: value)
                }
                
            }) { (data, error) in
                if failure != nil {
                    failure!(data: data)
                }
            }
            
            
//        }
       
    }
    
    //搜索 按类别
    
    func searchJobs(page page:Int,filterid:Int,filtertype:String,
                    success:((hasNextPage:Int,jobsArr:[NSDictionary])->Void),failure:((data:AnyObject)->())?) {
        
        let params = ["filterid":"\(filterid)","filtertype":filtertype,"page":"\(page)"]
        
        LDNetWorkManager.sharedInstance.LoginPOST(LDJobfinderAPI.discover.filter, parameters: params, success: { (value) in
            
            let data = value as? NSDictionary
            
            let hasNextPage = data!["hasNextPage"] as? Int ?? 0
            let jobsArr = data!["jobs"] as? [NSDictionary] ?? [NSDictionary]()
            
            success(hasNextPage: hasNextPage,jobsArr: jobsArr)
            
            
        }) { (data, error) in
            
            if failure != nil {
                
                failure!(data: data)
            }
        }
        
    }
    
    //搜索 筛选 ＋ 文本 
    /** filterid,filtertype 暂时穿空 暂时boss jobfinder统一处理 */
    func searchJobs(page page:Int,filterid:Int?,filtertype:String?,text:String,
                         success:((hasNextPage:Int,jobsArr:[NSDictionary])->Void),failure:((data:AnyObject)->())?) {
        
        var params = NSDictionary()
        
        if filtertype != nil {
            
            params = ["filterid":"\(filterid ?? 0)","filtertype":filtertype!,"page":"\(page)","search":text]
        } else {
            
            params = ["page":"\(page)","search":text]
        }
        
        var api = String()
        var key = String()
        
        
        if  DDClientInfoManager.clientType() == DDClientType.Cattle {
            
            api = LDJobfinderAPI.discover.search
            key = "jobs"
            
        } else {
            
            api = LDEmploryAPI.discover.jobfinders_search
            key = "jobfinders"
        }
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params as? Dictionary<String, AnyObject>, success: { (value) in
            
            let data = value as? NSDictionary
            
            let hasNextPage = data!["hasNextPage"] as? Int ?? 0
            let jobsArr = data![key] as? [NSDictionary] ?? [NSDictionary]()
            
            success(hasNextPage: hasNextPage,jobsArr: jobsArr)
            
            
        }) { (data, error) in
            
            if failure != nil {
                
                failure!(data: data)
            }
        }
        
    }
    //牛人端查询系统消息
    
    func querySystemMessage(success:((dict:[NSDictionary])->Void),failure:((error:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.systemMessage
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: nil, success: { (value) in
          
            success(dict: value as! [NSDictionary])
            
        }) { (data, error) in
            
            failure(error: data)
        }
        
    }
    
    //查询个推设置
    func queryGeTuiPushSetting(success:((dict:NSDictionary)->Void),failure:((error:AnyObject)->Void)?) {
        
        
        var api = ""
        
        if  DDClientInfoManager.clientType() == .Cattle {
            
            api = LDJobfinderAPI.query.getuiPush
        } else {
            
            api = LDEmploryAPI.query.getuiPush
        }
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: nil, success: { (value) in
            
            success(dict: value as! NSDictionary)
            
            if DDClientInfoManager.clientType() == .Cattle  {
                
                LDCacheManager.shareInstance.saveToCache("cattlequerygetuinotice", value: value as! NSDictionary, success: nil)
            } else {
                
                LDCacheManager.shareInstance.saveToCache("bossquerygetuinotice", value: value as! NSDictionary, success: nil)
            }
            
            
        }) { (data, error) in
            
            if DDClientInfoManager.clientType() == .Cattle  {
                
                LDCacheManager.shareInstance.readFromCache("cattlequerygetuinotice", colsure: { (key, value) in
                    
                    if value != nil {
                        
                        let dict = value as? NSDictionary ?? NSDictionary()
                        success(dict: dict)
                    } else {
                        
                        if failure != nil {
                            
                            failure!(error: data)
                        }
                    }
                })
                
            } else {
                
                LDCacheManager.shareInstance.readFromCache("bossquerygetuinotice", colsure: { (key, value) in
                    
                    if value != nil {
                        
                        let dict = value as? NSDictionary ?? NSDictionary()
                        success(dict: dict)
                    } else {
                        
                        if failure != nil {
                            
                            failure!(error: data)
                        }
                    }
                })
                
            }
        }
    }
    //设置个推设置
    func setGetuiPushSetting(params:NSDictionary,success:(()->Void),failure:((error:AnyObject)->Void)?) {
        
        var api = ""
    
        if  DDClientInfoManager.clientType() == .Cattle {
            
            api = LDJobfinderAPI.set.getuiPush
        } else {
            
            api = LDEmploryAPI.set.getuiPush
        }
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params as? Dictionary<String, AnyObject>, success: { (value) in
            
            success()
            
        }) { (data, error) in
            
            if failure != nil {
                
                failure!(error: data)
            }
        }
    }
    
    //设置发票抬头明细

    func getInvoiceInfo(id:String?,succ:((dictArr:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.invoiceInfo
        
        var params = ["":""]
        if id != nil {
            
            params = ["id":id!]
        }
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params, success: { (value) in
            
            succ(dictArr: value as! [String : AnyObject])
        }) { (data, error) in
            
            fail(err: data)
        }
        
    }
    
    //发起金额开票动作
    func submitInvoiceMoneyAmount(id:String?,params:Dictionary<String,AnyObject>? ,succ:((String)->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.set.submitInvoiceMoneyInfo
        
        var dict = params
        if id != nil && params != nil {
            
            dict!["invoice_id"] = id
        }
        
        LDNetWorkManager.sharedInstance.LoginPOSTSET(api, parameters: dict, success: { (value) in
            
            succ(value as? String ?? "成功")
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    //修改or 新建 设置默认 发票信息
    func editOrAddInvoiceBillInfo(id:String?,params:Dictionary<String, AnyObject>?,succ:((String)->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.set.selectedInvoiceInfo
        var dict = params
        if id != nil && params != nil {
            
            dict!["id"] = id
        }
        
        LDNetWorkManager.sharedInstance.LoginPOSTSET(api, parameters: dict, success: { (value) in
            
            succ(value as? String ?? "成功")
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    //得到账单信息列表
    func getInvoiceBillInfoList(succ:((dictArr:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.getInvoiceBillList
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: nil, success: { (value) in
            
            succ(dictArr: value as! [String : AnyObject])
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    //得到开票历史纪录列表
    func getInvoiceBillHistoryList(page:Int?,succ:((dictArr:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.getInvoiceBillHistoryList
        
        let dict = ["page":page ?? 0]
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: dict, success: { (value) in
            
            succ(dictArr: value as! [String : AnyObject])
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    //得到开票详情
    func getInvoiceBillHistoryListDetail(id:String?,succ:((dictArr:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.getInvoiceBillHistoryListDetail
        
        var params = ["":""]
        if id != nil {
            
            params = ["id":id!]
        }
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params, success: { (value) in
            
            succ(dictArr: value as! [String : AnyObject])
        }) { (data, error) in
            
            fail(err: data)
        }
        
    }
    
    
    
    //删除开票历史纪录
    func deleteInvoiceBillHistory(id:String,succ:((dictArr:String)->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.deleteInvoiceBillHistory
        
        let dict = ["id":id]
        LDNetWorkManager.sharedInstance.LoginPOSTSET(api, parameters: dict, success: { (value) in
            
            succ(dictArr: value as? String ?? "成功")
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    /**删除抬头信息*/
    func deleteInvoiceBillList(id:String,succ:((dictArr:String)->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.deleteInvoiceBillList
        
        let dict = ["id":id]
        LDNetWorkManager.sharedInstance.LoginPOSTSET(api, parameters: dict, success: { (value) in
            
            succ(dictArr: value as? String ?? "成功")
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    /**请求面试列表*/
    func getInterviewInfoList(params:Dictionary<String,String>?,succ:((dict:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.getInterviewList
        
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params, success: { (value) in
            
            succ(dict: value as! [String : AnyObject])
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    /**请求面试列表详情*/
    func getInterviewInfoListDetail(id:String,succ:((dict:[String:AnyObject])->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.getInterviewListDetail
    
        let params = ["id":id]
        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params, success: { (value) in
            
            succ(dict: value as! [String : AnyObject])
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    /**保存面试 可编辑*/
    func editAndSaveInterviewInfoDetail(params:Dictionary<String,String>,succ:((idDict:NSDictionary)->Void),fail:((err:AnyObject)->Void)) {
        
        let api = LDJobfinderAPI.query.editAndSaveInterviewListDetail

        LDNetWorkManager.sharedInstance.LoginPOST(api, parameters: params, success: { (value) in
            
            succ(idDict: value as! NSDictionary)
        }) { (data, error) in
            
            fail(err: data)
        }
    }
    
    
    
    
    
    
}